<script setup>
import { ref } from 'vue';

import {onPullDownRefresh} from '@dcloudio/uni-app'

	const jokeText = ref('')
	
	const getJoke = async () => {
		//开启加载动画
		uni.showLoading({ title:'笑话加载中...'})
		//发起网络请求
		const res = await uni.request({
			method:'GET',
			url:'https://api-vue-base.itheima.net/api/joke',
			data:{}
		})
			console.log(res)
			//把后端返回的数据赋值给ref ,数据驱动视图
			jokeText.value = res.data
			//关闭加载动画
			uni.hideLoading()
		
	}
	//先调用一次获取笑话
	getJoke()
	
	const jokeList = ref([])
	//获取多条笑话
	const getJokeList = async () => {
		uni.showLoading({title:'笑话加载中...'})
		//发送网络请求
		const res = await uni.request({
			method:'GET',
			url:'https://api-vue-base.itheima.net/api/joke/list',
			data:{ num: 3 } //请求参数
		})
			console.log(res)
			jokeList.value = res.data.data
			uni.hideLoading()
		
	}
	
	getJokeList()
	
	//下拉刷新事件
	onPullDownRefresh(async () => {
		uni.showNavigationBarLoading()
		//重新获取数据
		await Promise.all([getJoke(),getJokeList()]) 
		
		//关闭loading 提示
		uni.hideNavigationBarLoading()
		//数据获取成功，关闭下拉刷新效果
		uni.stopPullDownRefresh()
	})
</script>

<template>
	<view class="joke column">
		<image class="joke-image" src="/static/joke.jfif" mode=""></image>
		<text class="joke-text">{{jokeText}}</text>
		<button class="joke-button" v-if="jokeText" @click="getJoke()" type="primary">换个笑话</button>
		<!-- 获取多条笑话 -->
		
		<!-- <button  @click="getJokeList()" type="warn">获取笑话列表</button> -->
		<!-- 注意：判断数组非空，需要判断数组的长度是否大于 0 -->
		<button  v-if="jokeList.length > 0 " @click="getJokeList()" type="warn">换组笑话列表</button>
		<view class="joke-list">
			<view class="joke-item" v-for="item in jokeList" :key="item">
				笑话:{{ item }}
			</view>
		</view>
	</view>
</template>



<style lang="scss">
	.joke{
		padding: 20rpx;
		align-items: center;
		
		.joke-image{
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 20rpx;
		}
		.joke-button{
			background-color: $uni-color-primary;
			margin-bottom: 20rpx;
		}
		.joke-item{
			border-bottom: 1px solid #f60;
			padding: 20rpx;
		}
	}
	
</style>
